package com.ttl.common.menu;

import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.navigator.menu.MenuComponent;
import net.sf.navigator.menu.MenuRepository;

public class MenuCreate {
	
	@SuppressWarnings("unchecked")
	public static MenuRepository create(HttpServletRequest request, HttpServletResponse response, List menuNew) {
				
		ServletContext application = request.getSession().getServletContext();
				
        MenuRepository repository = new MenuRepository();
        // Get the repository from the application scope - and copy the
        // DisplayerMappings from it.
        MenuRepository defaultRepository = (MenuRepository)
                application.getAttribute(MenuRepository.MENU_REPOSITORY_KEY);
        repository.setDisplayers(defaultRepository.getDisplayers());
                                        			                      
        //######### START 
//        MenuDAO dao = new MenuDAO();//add         
//        String hql = "FROM MenuBean m order by m.id";//add
//        List menuNew = dao.find(hql);//add            
        
        for (int i=0; i < menuNew.size(); i++) {
        	MenuComponent mc = new MenuComponent();
        	MenuBean menuBean = (MenuBean)menuNew.get(i); 
        	String name = menuBean.getName();
        	mc.setName(name);
        	
        	String parent = menuBean.getParent_name();
        	if (parent != null) {
                MenuComponent parentMenu = repository.getMenu(parent);
                if (parentMenu == null) {
                    //System.out.println("parentMenu '" + parent + "' doesn't exist!");
                    // create a temporary parentMenu
                    parentMenu = new MenuComponent();
                    parentMenu.setName(parent);
                    repository.addMenu(parentMenu);                    
                }
                mc.setParent(parentMenu);        		
        	}
            String title = menuBean.getTitle();
            mc.setTitle(title);
            String location = menuBean.getLocation();
            mc.setLocation(location);
            repository.addMenu(mc);        	       	
        }
        //######### END :
        
		return repository;
	}
}
